package com.atguigu.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * @USER: dayu Administrator
 * @DATE: 2020/3/26
 * @DESCRIPTION:
 */
@Service
public class PaymentHystrixService {

    @Value("${server.port}")
    String serverPort;

    public String getOk(Long id) {
        return Thread.currentThread().getName() + "\t" + id + "\t 处理成功";
    }

    /**
     * 当服务超时或者服务不可用的时候，都会触发服务降级，切换到fallbackMethod中
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentInfoTimeoutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public String paymentInfoTimeout(Long id) {
        //休息会。。。
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        int a = 10 / 0;
        return Thread.currentThread().getName() + "\t" + id + "\t 处理超时";
    }

    public String paymentInfoTimeoutHandler(Long id) {
        return "线程池：" + Thread.currentThread().getName() + "：程序运行报错或者超时了， fallback:paymentInfoTimeoutHandler \tid: " + id + "";
    }


    //服务熔断
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数。使用统计信息做出打开/关闭决定之前，必须在statisticalWindow内发出的请求数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//电路跳闸后的毫秒数，然后允许重试
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")//不能使电路跳闸的“标记”的百分比
    })
    public String paymentCircuitBreaker(Long id){
        if(id<0){
            throw new RuntimeException("id 不能为负数！！！！");
        }
        //生成一个唯一的流水号
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName()+" 调用成功，流水号："+serialNumber;
    }


    //服务熔断
    public String paymentCircuitBreaker_fallback(Long id){
        return "id 不能为负数，请稍后再试试: id:"+id;
    }



}
